package sc.client;

import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;

import k8.k8;
import k8.Logic;
import k8.util.Camera;

public final class Interface extends Logic
{
	// The single instance of Interface
	private static Interface instance = null;

	// Camera sensitivity
	private final float movementSpeed = 0.00000001f;
	
	// The camera
	public static Camera camera;

	private int dx, dy;
	private long lastupdate;
	private long elapsed;
	private HUD hud;

	/** Prevent public construction of Interface */
	private Interface()
	{
		// Create a Camera and attach it to the player Avatar
		camera = Camera.getInstance();
		Client.avatar.add(camera);

		// Create the HUD just a little further than near clipping plane
		hud = new HUD(camera.getNearClip() + 0.1f);
		camera.add(hud.layer);

		// Update the interface 10 times a second
		setUpdateRate(10);
	}

	/**
	 * Creates a single instance of Interface.
	 */
	public static void initialise()
	{
		if (instance == null)
			instance = new Interface();
	}

	@Override
	public void update(long time)
	{
		// Calculate elapsed time
		elapsed = time - lastupdate;
		lastupdate = time;
		
		// Check for mouse events
		while (Mouse.next())
		{
			switch (Mouse.getEventButton())
			{
			case 0:
				Mouse.setGrabbed(Mouse.getEventButtonState());
				break;
			}
		}
		
		// Check for keyboard events
		while (Keyboard.next())
		{
			// Ignore keydown events
			if (Keyboard.getEventKeyState())
				continue;

			switch (Keyboard.getEventKey())
			{
			case Keyboard.KEY_ESCAPE:
				k8.finish();
				break;
			}
		}
		
		if (Keyboard.isKeyDown(Keyboard.KEY_E))
			Client.avatar.moveForward(movementSpeed * elapsed);
		else if (Keyboard.isKeyDown(Keyboard.KEY_D))
			Client.avatar.moveForward(-movementSpeed * elapsed);
		if (Keyboard.isKeyDown(Keyboard.KEY_S))
			Client.avatar.moveRight(-movementSpeed * elapsed);
		else if (Keyboard.isKeyDown(Keyboard.KEY_F))
			Client.avatar.moveRight(movementSpeed * elapsed);
		if (Keyboard.isKeyDown(Keyboard.KEY_Q))
			Client.avatar.moveUp(movementSpeed * elapsed);
		else if (Keyboard.isKeyDown(Keyboard.KEY_A))
			Client.avatar.moveUp(-movementSpeed * elapsed);

		// Mouse look if grabbed
		if (Mouse.isGrabbed())
		{
			dx = Mouse.getDX();
			dy = Mouse.getDY();

			if (dx != 0)
				Client.avatar.yaw(-dx / 100f);

			if (dy != 0)
				camera.pitch(-dy / 100f);
		}
	}

	/**
	 * Returns the camera.
	 * 
	 * @return the camera
	 */
	public Camera getCamera()
	{
		return camera;
	}
}